<?php
	require_once "../include/User.php";
	require_once "../include/Password.php";
	require_once "../include/backend/UserDb.php";
	require_once "../include/functions.php";
	
	// Logging out if that action is specified, else we'll try logging in
	if ($_GET['act'] == "logout") {
		session_start();
		session_destroy();
		header("Location: ../");
		die();
	}
	
	// If empty strings, redirect back to login page with error msg
	$pass = trim($_POST['pass']);
	
	if (!hasVal($_POST['username']) || !hasVal($pass)) {
		header("Location: ../login.php?err=empty");
		die();
	}
	
	$pass = new Password($pass); $pass = $pass->getHash();
	$users = new UserDb();
	$user = new User(array('username' => $_POST['username'], 'pass' => $pass));
	// user_db is the user gotten from the db
	$user_db = $users->get(new User(array('username' => strtolower($_POST['username']), 
	                                      'pass' => $pass))); 
	
	// If the user gotten from the database is not null valued, then the query
	// succeeded, thus a user with un/pw exists and we can log in
	if ($user_db->name == strtolower($user->name) && $user_db->pass == $user->pass) {
	    session_start();
	    $user_db->name = $_POST['username'];
	    $user_db->setLoggedIn(true);
	    $_SESSION['user'] = $user_db;
	    header("Location: ../login.php?stat=loggedin");
	}
	else
		header("Location: ../login.php?err=pwmismatch");
?>
